#!/usr/bin/env python

from re import search
import pdb


class MapTableManager(object):
	def __init__(self, map_table, base_id_regex=None):
		assert isinstance(map_table,list),"test_case must be a list."
		self.test_case_ = map_table
		# current position for output_list of current test_case.
		self.base_id_regex_ = base_id_regex
		self.curr_pos_name_ = "curr_pos"
		self.addPosFlagToMaptable()

	def addPosFlagToMaptable(self):
		for item in self.test_case_:
			item[self.curr_pos_name_] = 0


	def updateSingleCondition(self,input_command,item_condition):
		return  # Invalid Now
		assert isinstance(item_condition,dict),"item_condition must be a dict."
		for i in item_condition.keys():
			# Sbit condition, need to set mutual exclusion.
			if item_condition[i]==1:
				pass
			# Normal condition, just set as True
			if i==input_command:
				item_condition[i] = True


	def updateTestCaseCondition(self,input_command):
		"""TODO: Cause about arm_board&power_board&dut_board have affect each other. So 
			there are still problem for add Condition_list for command. We just
			cut this function off now.
		"""
		return # Invalid Now
		assert isinstance(input_command,str),"input_command must be a string."

		for item in self.test_case_:
			assert isinstance(item,dict),"Every item for test_case must be a dict."
			item_condition = item["condition_list"]
			self.updateSingleCondition(input_command,)


	def isConditionAvailable(self,item_condition):
		for key in item_condition.keys():
			if not item_condition[key]:
				return False

		return True


	def getNextVal(self,item):
		# TODO bounds checking
		output_list = item["output_list"]
		curr_pos = item[self.curr_pos_name_]
		max = len(output_list)
		if curr_pos<0 or curr_pos>=max:
			item[self.curr_pos_name_] = 0

		if len(output_list)==0:
			# Output_list is empty, so return default value.
			return item["default_output"]

		item[self.curr_pos_name_] = item[self.curr_pos_name_]+1
		return output_list[curr_pos]


	def getResponseString(self,input_command):
		# Input check
		if not isinstance(input_command,str):
			print("Error: 'input_command' must be a string.")
			raise TypeError("invalid type for input string.")
		# Extract ID & update condition for this Current TestCase.
		if self.base_id_regex_!=None:
			if search(self.base_id_regex_, input_command)==None:
				print("Require a valid ID for input_command")
				default_val = self.test_case_[-1]["default"]
				return default_val

		self.updateTestCaseCondition(input_command)
		# Get result
		for item in self.test_case_:

			#pdb.set_trace()
			if "command" in item.keys() and "condition_list" in item.keys() and "output_list" in item.keys():
				# Get input_command & condition & output
				item_command = item["command"]
				item_condition = item["condition_list"]
				item_output = item["output_list"]

				regex_ret = search(item_command,input_command)
				if regex_ret:
					if self.isConditionAvailable(item_condition):
						# Condition is available, return accorrding to output_list.
						print("Regex > {0}".format(item_command))
						print("Regex Ret > {0}".format(regex_ret.group(0)))
						if self.base_id_regex_!=None:
							ret_str = regex_ret.group(1)+self.getNextVal(item)
						else:
							ret_str = self.getNextVal(item)

						return ret_str
					else:
						# Condition is not available, abandon this.
						pass

		# TODO: Can't match , Return default value
		#pdb.set_trace()
		if self.base_id_regex_!=None:
			id_str = search(self.base_id_regex_, input_command).group(1)
			default_val = self.test_case_[-1]["default"]
			reponse_str = id_str + default_val
		else:
			reponse_str = self.test_case_[-1]["default"]

		return reponse_str
